#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QMessageBox>
#include <QDateTime>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_udpThread(new UdpThread())
{
    ui->setupUi(this);

    connect(ui->pushButton_connect, &QPushButton::clicked, this, &MainWindow::Slot_connect);
    connect(ui->pushButton_close, &QPushButton::clicked, this, &MainWindow::Slot_disconnect);
    connect(ui->pushButton_send, &QPushButton::clicked, this, &MainWindow::Slot_send);
    connect(m_udpThread.data(), &UdpThread::Sig_receive, this, &MainWindow::Slot_receive);
    connect(m_udpThread.data(), &UdpThread::Sig_errorCur, this, [=](QString error){
        QMessageBox::warning(this, "错误", error);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::Slot_connect()
{
    m_udpThread->SetLocalPort(ui->lineEdit_localPort->text().toShort());
    m_udpThread->SetDestinationIpPort(ui->lineEdit_destIp->text(), ui->lineEdit_destPort->text().toShort());
    bool res = m_udpThread->Connect();
    if(!res){
        QMessageBox::warning(this, "提示", "连接失败");
    }else{
        QMessageBox::information(this, "提示", "连接成功");
    }
}
void MainWindow::Slot_disconnect()
{
    if(m_udpThread->DisConnect()){
        QMessageBox::information(this, "提示", "断开成功");
    }else{
        QMessageBox::warning(this, "提示", "断开失败");
    }
}
void MainWindow::Slot_receive(QByteArray data)
{
    QDateTime time = QDateTime::currentDateTime();
    QString res = time.toString("yyyy-MM-dd hh:mm:ss.zzz") + " " + QString::fromLocal8Bit(data) + "\n";
    ui->textEdit_recv->append(res);
}
void MainWindow::Slot_send()
{
    QByteArray data = ui->textEdit_send->toPlainText().toLocal8Bit();
    m_udpThread->SendData(data);
}